package com.jrx.anytxn.investor.mq;

import com.jrx.anytxn.common.exception.TxnRuntimeException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.investor.entity.TlPaymentInvestorLog;
import com.jrx.anytxn.investor.mapper.ext.ExtTlPaymentInvestorLogMapper;
import com.jrx.anytxn.investor.service.IInvestorPaymentService;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import com.jrx.anytxn.transaction.entity.TlPaymentAllocationLog;
import com.jrx.anytxn.transaction.entity.TlWaivePaymentLog;
import com.jrx.anytxn.transaction.entity.TlWaivePaymentMapping;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanMainInfoMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentAllocationLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlWaivePaymentMappingMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
@RocketMQMessageListener(
        topic = TransBizConstant.MQ_INVESTOR_WAIVE_PAYMENT_TOPIC + "${spring.cloud.nacos.discovery.metadata.currentVersion}",
        consumerGroup = TransBizConstant.MQ_INVESTOR_WAIVE_PAYMENT_GROUP + "${spring.cloud.nacos.discovery.metadata.currentVersion}",
        consumeThreadMax = 5
)
public class InvestorWaivePaymentMqConsumerService implements RocketMQListener<String> {

    private static final Logger logger = LoggerFactory.getLogger(InvestorWaivePaymentMqConsumerService.class);

    @Autowired
    private IInvestorPaymentService investorPaymentService;
    @Autowired
    private ISegmentService segmentService;
    @Autowired
    private ExtTlWaivePaymentMappingMapper extWaivePaymentMappingMapper;
    @Autowired
    private ExtTlPaymentAllocationLogMapper exttlPaymentAllocationLogMapper;
    @Autowired
    private ExtAmLoanMainInfoMapper extAmLoanMainInfoMapper;
    @Autowired
    private ExtTlPaymentInvestorLogMapper extTlPaymentInvestorLogMapper;

    @Override
    public void onMessage(String jSonMessage){

        logger.debug("MQ消费端获取到贴息还款请求 ：{}",jSonMessage);

        // json转换成并bean
        TlWaivePaymentLog bean;
        try {
            bean = JsonUtils.json2pojo(jSonMessage, TlWaivePaymentLog.class);
        } catch (Exception e) {
            logger.error("MQ消费端JSon转换异常 ：{}",e);
            throw new TxnRuntimeException("MQ消费端JSon转换异常");
        }

        List<TlWaivePaymentMapping>  waivePaymentMappingList = extWaivePaymentMappingMapper.selectByPaymentSeqAndCustomerId(bean.getSeqNo(),bean.getCustomerId(),bean.getTenantId());

        for(TlWaivePaymentMapping mapping : waivePaymentMappingList) {

            AmLoanMainInfo info = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(mapping.getLoanId(),mapping.getCustomerId(),mapping.getTenantId());
            if(TransBizConstant.JOINT_LOAN_FLAG_0.equals(info.getJointLoanFlag())){
                continue;
            }

            // 联合贷授信
            try {
                TlPaymentInvestorLog log = extTlPaymentInvestorLogMapper.selectByCustSeqNoAndLoanId(bean.getSeqNo(),mapping.getLoanId(),mapping.getCustomerId(),mapping.getTenantId());
                if(null == log) {
                    log = new TlPaymentInvestorLog();
                    BeanMapping.copy(bean, log);
                    log.setLoanId(mapping.getLoanId());
                    List<TlPaymentAllocationLog> tlPaymentAllocationLogList = exttlPaymentAllocationLogMapper.findCustLog(mapping.getLoanId(), bean.getSeqNo(), bean.getCustomerId(), bean.getTenantId());
                    BigDecimal totalAmt = tlPaymentAllocationLogList.stream().map(TlPaymentAllocationLog::getPostingAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    log.setTotalAmount(totalAmt);
                    log.setCustPaymentSeqNo(bean.getSeqNo());
                    log.setId(segmentService.getId(com.jrx.anytxn.investor.constant.TransBizConstant.TL_PAYMENT_INVESTOR_LOG));
                    log.setSeqNo(TransBizConstant.PAYMENT_LOG_SEQ_PREFIX + SeqUtils.getSNByLength(TransBizConstant.PAYMENT_LOG_SEQ_RADOM_LENGTH));
                    log.setPaymentSource("1"); // 还款来源 0=客户 1=贴息
                    log.setCreateTime(null);
                    log.setUpdateTime(null);
                    log.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
                    //保存还款流水
                    extTlPaymentInvestorLogMapper.insertSelective(log);
                }
                investorPaymentService.paymentAllocation(log);
            } catch (Exception e) {
                logger.error("MQ消费端，客户id[{}]，客户还款流水号[{}],合作行还款异常：{}", bean.getCustomerId(), bean.getSeqNo(), e);
                throw new TxnRuntimeException("合作行还款异常");
            }
        }
    }

}
